package com.api.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import com.api.demo.dto.FileUploadResponse;
import com.api.demo.service.FileStorageService;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/files")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class FileController {

    @Value("${file.upload-dir:uploads/avatars}")
    private String uploadDir;

    @Autowired
    private FileStorageService fileStorageService;

    @PostMapping("/upload/avatar")
    public ResponseEntity<?> uploadAvatar(@RequestParam("file") MultipartFile file) {
        try {
            System.out.println("开始处理文件上传: " + file.getOriginalFilename() + ", 大小: " + file.getSize() + " bytes");
            
            if (file.isEmpty()) {
                System.err.println("收到空文件");
                Map<String, String> error = new HashMap<>();
                error.put("error", "文件为空");
                return ResponseEntity.badRequest().body(error);
            }

            // 确保目录存在
            String projectDir = new File("").getAbsolutePath();
            File directory = new File(projectDir, uploadDir);
            if (!directory.exists()) {
                System.out.println("创建目录: " + directory.getAbsolutePath());
                directory.mkdirs();
            }
            
            // 同时在target/classes目录下创建目录
            try {
                File classesDir = new File(projectDir, "target/classes/" + uploadDir);
                if (!classesDir.exists()) {
                    System.out.println("创建classes目录: " + classesDir.getAbsolutePath());
                    classesDir.mkdirs();
                }
            } catch (Exception e) {
                System.err.println("创建classes目录失败: " + e.getMessage());
            }
            
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
            String newFilename = UUID.randomUUID().toString() + fileExtension;
            
            // 保存文件
            File targetFile = new File(directory, newFilename);
            System.out.println("保存文件到: " + targetFile.getAbsolutePath());
            Files.copy(file.getInputStream(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
            
            // 同时复制到target/classes目录
            try {
                File classesTargetFile = new File(projectDir, "target/classes/" + uploadDir + "/" + newFilename);
                Files.copy(targetFile.toPath(), classesTargetFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                System.out.println("复制文件到classes: " + classesTargetFile.getAbsolutePath());
            } catch (Exception e) {
                System.err.println("复制到classes目录失败: " + e.getMessage());
            }
            
            // 构建URL
            String avatarUrl = "/api/files/avatars/" + newFilename;
            System.out.println("文件上传成功, URL: " + avatarUrl);
            
            Map<String, String> response = new HashMap<>();
            response.put("avatarUrl", avatarUrl);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            System.err.println("文件上传失败: " + e.getMessage());
            e.printStackTrace();
            
            Map<String, String> error = new HashMap<>();
            error.put("error", "文件上传失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(error);
        }
    }

    @PostMapping("/upload")
    public ResponseEntity<FileUploadResponse> uploadFile(
            @RequestParam("file") MultipartFile file,
            Authentication authentication) {
        
        String fileUrl = fileStorageService.storeFile(file);
        
        FileUploadResponse response = new FileUploadResponse(
            file.getOriginalFilename(),
            fileUrl,
            file.getContentType(),
            file.getSize()
        );
        
        return ResponseEntity.ok(response);
    }
    
    @PostMapping("/upload/{directory}")
    public ResponseEntity<FileUploadResponse> uploadFileToDirectory(
            @RequestParam("file") MultipartFile file,
            @PathVariable String directory,
            Authentication authentication) {
        
        String fileUrl = fileStorageService.storeFile(file, directory);
        
        FileUploadResponse response = new FileUploadResponse(
            file.getOriginalFilename(),
            fileUrl,
            file.getContentType(),
            file.getSize()
        );
        
        return ResponseEntity.ok(response);
    }
} 